<template>
  <el-container class="hy-container">
    <div class="handleDiv">
      <div>
        <span>完善陈品信息</span>
      </div>
      <div class="timeline" v-if="step==2">
        <div class="precent"></div>
        <div class="item" style="margin-left: -25px;">
          <div class="dot" style="background: #2878FF;"></div>
          <div>表头匹配</div>
        </div>
        <div class="item" style="margin-right: -25px;">
          <div class="dot"></div>
          <div>导入数据</div>
        </div>
      </div>
      <div>
        <template v-if="step==1">
          <el-button size="medium" @click="openGetDialog">获取产品信息</el-button>
          <el-button size="medium" @click="importExcel">excel本地导入</el-button>
          <el-button size="medium" @click="back">返回</el-button>
        </template>
        <template v-if="step==2">
          <el-button type="primary" size="medium" @click="confirmMatche">确认匹配</el-button>
          <el-button size="medium" @click="returnStep">返回</el-button>
        </template>
        <template v-if="step==3">
          <el-button size="medium" type="primary" @click="save">保存到产品库</el-button>
          <el-button size="medium" type="warning" @click="cancelSave">离开</el-button>
        </template>
      </div>
    </div>
    <div class="tableArea" style="padding:15px" v-loading="tableLoading">
      <template v-if="step==1">
        <img class="noData_img" src="../../assets/images/nodata.png" />
        <div class="noData">当前没有数据</div>
        <el-button style="margin-top:30px" @click="openGetDialog">获取产品信息</el-button>
      </template>
      <div class="headerMatche" v-if="step==2">
        <el-card class="matcheCard">
          <el-row>
            <el-col :span="12">
              <div class="matcheItem" style="font-size:14px;">
                <div class="title">产品信息</div>
                <div>表格中对应的表头</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="matcheItem" style="font-size:14px;">
                <div class="title">产品信息</div>
                <div>表格中对应的表头</div>
              </div>
            </el-col>
            <el-col :span="12" v-for="(item,index) in templateHeaderList" :key="index">
              <div class="matcheItem">
                <div class="title">{{item}}</div>
                <img src="../../assets/images/path@3x.png" />
                <el-select v-model="confirmImportHeadList[index]" placeholder="请选择" clearable>
                  <el-option
                    v-for="(item,index) in importHeadList"
                    :key="index"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </div>
      <likeExcel
        ref="mychild"
        v-if="step==3"
        :excelData="dataList"
        :excelHeaders="templateHeaderList"
        :maxLength="maxRows"
        :dataSource="dataSource"
      ></likeExcel>
    </div>
    <!-- 批量导入 -->
    <el-dialog
      class="text-left product"
      title="批量导入产品"
      :visible.sync="dialogVisible"
      top="7vh"
      width="700px"
    >
      <span>在Excel表格中添加多条产品，即可上传文件一次性导入产品到产品库。</span>
      <el-upload
        ref="inputer"
        :auto-upload="false"
        class="upload-demo"
        :on-change="elInFile"
        :show-file-list="false"
        :file-list="fileList"
        :limit="1"
        accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        drag
        action="https://jsonplaceholder.typicode.com/posts/"
        multiple
      >
        <img style="width:160px;margin-bottom:30px" src="../../assets/images/import.png" />
        <div class="el-upload__text">
          <p>拖动.xlsx 文件到这里进行上传</p>
          <p>
            你还可以
            <em>手动选择文件上传</em>
          </p>
        </div>
      </el-upload>
      <div>
        <span>推荐使用</span>
        <span class="downLoad" @click="exportTemplete">产品库批量导入模板</span>整理数据。如自行整理，请确保表格每一行为一个产品。
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      class="text-left product"
      title="获取产品信息"
      :visible.sync="getInfoDialog"
      top="7vh"
      width="700px"
    >
      <div style="height:400px">
        <div style="margin-bottom:50px">在办公相机中所拍产品，根据筛选进行一次性获取并导入产品到产品库。</div>
        <div class="hy_item">
          <label>筛选</label>
          <el-radio-group v-model="formData.verify">
            <el-radio :label="true">已审批</el-radio>
            <el-radio :label="false">待审批</el-radio>
          </el-radio-group>
        </div>
        <div class="hy_item">
          <label>供应商</label>
          <el-select v-model="formData.supplier" filterable placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.custsimpname"
              :value="item.id"
            ></el-option>
          </el-select>
        </div>
        <div class="hy_item">
          <label>时间</label>
          <el-date-picker
            v-model="eldate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <div class="footerLeft">
          <p class="themeCol getAll" @click="search('all')">获取全部产品</p>
          <p class="colDesc">不受条件限制获取全部供应商产品</p>
        </div>
        <el-button @click="getInfoDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmProduct">确定</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
/* eslint-disable */
import { likeExcel } from "@/components/likeExcel/index";
import Handsontable from "handsontable-pro";
import store from "@/utils/factory";
import config from "@/config/index";
import apiMethod from "@/api/apiMethod";
import { fuzzysearch } from "@/api/login";
import {
  getBatchTitle,
  batchUpdate,
  query,
  exportTemplete
} from "@/api/product";
export default {
  computed: {},
  name: "importPage",
  components: {
    likeExcel: likeExcel
  },
  data() {
    return {
      importLoading: false,
      formData: {},
      postData: [],
      outDataList: [],
      dialogVisible: false,
      getInfoDialog: false,
      file: "",
      step: 1,
      defaultImg: require("@/assets/images/noImg.png"),
      options: [],
      sourceOptions: [],
      maxRows: 9999,
      havaData: false,
      value: "",
      fileList: [],
      headerList: [],
      importHeadList: [],
      dataSource: [],
      tableLoading: false,
      confirmImportHeadList: [],
      dataList: [],
      templateHeaderList: [],
      allTemplateHeaderList: [],
      radio: 3,
      eldate: [],
      transforId: {},
      type: "" // 1.新增 2.编辑
    };
  },
  created() {
    let self = this;
    this.getfuzzy();
    getBatchTitle().then(res => {
      self.templateHeaderList = res.rows;
    });
  },
  mounted() {
    console.log(document.documentElement.clientHeight - 152);
  },
  methods: {
    exportTemplete() {
      exportTemplete()
        .then(result => {
          //创建一个blob对象,file的一种
          let blob = new Blob([result.data], { type: "application/x-xls" });
          let link = document.createElement("a");
          link.href = window.URL.createObjectURL(blob); //配置下载的文件名
          link.download = "产品库批量导入模板.xlsx";
          link.click();
          link.remove();
        })
        .catch(e => {});
    },
    confirmMatche() {
      let self = this;
      let a = [];
      this.outDataList.map((item, index) => {
        a[index] = {
          name: item[this.confirmImportHeadList[0]],
          picture: item[this.confirmImportHeadList[1]],
          price: item[this.confirmImportHeadList[2]],
          productLength: item[this.confirmImportHeadList[3]],
          productWidth: item[this.confirmImportHeadList[4]],
          productHeight: item[this.confirmImportHeadList[5]],
          inBoxQuantity: item[this.confirmImportHeadList[6]],
          outBoxQuantity: item[this.confirmImportHeadList[7]],
          outBoxLength: item[this.confirmImportHeadList[8]],
          outBoxWidth: item[this.confirmImportHeadList[9]],
          outBoxHeight: item[this.confirmImportHeadList[10]],
          netWeight: item[this.confirmImportHeadList[11]],
          grossWeight: item[this.confirmImportHeadList[12]],
          material: item[this.confirmImportHeadList[13]],
          minOrder: item[this.confirmImportHeadList[14]],
          unit: item[this.confirmImportHeadList[15]],
          supplier: item[this.confirmImportHeadList[16]],
          remark: item[this.confirmImportHeadList[17]]
        };
      });
      this.headerList = this.templateHeaderList;
      this.dataList = a;
      this.dataSource = [
        { data: "name", readOnly: false, type: "text" },
        { data: "picture", readOnly: false, renderer: this.coverRenderer },
        { data: "price", readOnly: false, type: "numeric" },
        { data: "productLength", readOnly: false, type: "numeric" },
        { data: "productWidth", readOnly: false, type: "numeric" },
        { data: "productHeight", readOnly: false, type: "numeric" },
        { data: "inBoxQuantity", readOnly: false, type: "numeric" },
        { data: "outBoxQuantity", readOnly: false, type: "numeric" },
        { data: "outBoxLength", readOnly: false, type: "numeric" },
        { data: "outBoxWidth", readOnly: false, type: "numeric" },
        { data: "outBoxHeight", readOnly: false, type: "numeric" },
        { data: "netWeight", readOnly: false, type: "numeric" },
        { data: "grossWeight", readOnly: false, type: "numeric" },
        { data: "material", readOnly: false },
        { data: "minOrder", readOnly: false, type: "numeric" },
        { data: "unit", readOnly: false, type: "text" },
        {
          data: "supplier",
          readOnly: false,
          type: "dropdown",
          source: this.sourceOptions,
          strict: false
        },
        { data: "remark", readOnly: false, type: "text" }
      ];
      this.step = 3;
    },
    back() {
      this.$router.back(-1);
    },
    getfuzzy() {
      let self = this;
      const formData = new FormData();
      let params = {
        method: apiMethod.getfuzzy,
        terminalType: 1
      };
      params = Object.assign(config.commonParmas, params);
      Object.keys(params).forEach(key => {
        formData.append(key, params[key]);
      });
      fuzzysearch(formData).then(res => {
        res.data.map(item => {
          self.sourceOptions.push(item.custsimpname);
          self.transforId[item.custsimpname] = item.id;
        });
        self.options = res.data;
      });
    },
    confirmProduct() {
      let postData = {
        ...this.formData,
        time: {
          max: this.eldate.length > 0 ? this.eldate[1].getTime() : "",
          min: this.eldate.length > 0 ? this.eldate[0].getTime() : ""
        }
      };
      this.search(postData);
    },
    returnStep() {
      let self = this;
      this.$confirm("是否返回?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        self.clearAll();
        self.step = 1;
      });
    },
    openGetDialog() {
      this.clearAll();
      this.getInfoDialog = true;
    },
    clearAll() {
      this.headerList = [];
      this.importHeadList = [];
      this.dataList = [];
      this.fileList = [];
    },
    batchUpdate(a) {
      batchUpdate({ products: a })
        .then(res => {
          this.$message({
            type: "success",
            message: this.type == 1 ? "新增成功!" : "编辑保存成功!"
          });
          this.clearAll();
          this.tableLoading = false;
          this.step = 1;
        })
        .catch(err => {
          this.tableLoading = false;
        });
    },
    save() {
      let self = this;
      this.postData = [];
      this.$confirm("是否保存到产品库?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success"
      })
        .then(() => {
          self.$refs.mychild.saveData();
          if (self.$refs.mychild.allData.length == 0) {
            self.$message.error("请上传至少一条数据!");
            return false;
          }
          self.tableLoading = true;
          let a = [];
          a = self.$refs.mychild.allData;
          a.map(item => {
            if (self.transforId[item.supplier]) {
              item.supplier = self.transforId[item.supplier];
            }
          });
          self.batchUpdate(a);
        })
        .catch(() => {});
    },
    cancelSave() {
      this.$confirm("是否取消保存?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "danger"
      })
        .then(() => {
          this.clearAll();
          this.step = 1;
        })
        .catch(() => {});
    },
    search(params) {
      let self = this;
      this.type = 2;
      let obj = {};
      if (params != "all") {
        obj = { ...params, resultAll: true };
        if (this.templateHeaderList.indexOf("货号") == -1) {
          this.templateHeaderList.unshift("货号");
        }
      } else {
        obj = { resultAll: true };
        if (this.templateHeaderList.indexOf("货号") != -1) {
          this.templateHeaderList.splice(
            this.templateHeaderList.indexOf("货号"),
            1
          );
        }
      }
      this.headerList = this.templateHeaderList;
      this.dataSource = [
        { data: "code", readOnly: true, type: "text" },
        { data: "name", readOnly: false, type: "text" },
        { data: "picture", readOnly: false, renderer: this.coverRenderer },
        { data: "price", readOnly: false, type: "numeric" },
        { data: "productLength", readOnly: false, type: "numeric" },
        { data: "productWidth", readOnly: false, type: "numeric" },
        { data: "productHeight", readOnly: false, type: "numeric" },
        { data: "inBoxQuantity", readOnly: false, type: "numeric" },
        { data: "outBoxQuantity", readOnly: false, type: "numeric" },
        { data: "outBoxLength", readOnly: false, type: "numeric" },
        { data: "outBoxWidth", readOnly: false, type: "numeric" },
        { data: "outBoxHeight", readOnly: false, type: "numeric" },
        { data: "netWeight", readOnly: false, type: "numeric" },
        { data: "grossWeight", readOnly: false, type: "numeric" },
        { data: "material", readOnly: false },
        { data: "minOrder", readOnly: false, type: "numeric" },
        { data: "unit", readOnly: false, type: "text" },
        {
          data: "supplier",
          readOnly: false,
          type: "dropdown",
          source: this.sourceOptions,
          strict: false
        },
        { data: "remark", readOnly: false, type: "text" }
      ];
      query(obj).then(res => {
        if (res.data.products.length == 0) {
          self.$message.error("没有查询到相关数据");
          return false;
        }
        self.getInfoDialog = false;
        self.maxRows = res.data.products.length;
        self.dataList = res.data.products;
        self.step = 3;
      });
    },
    handleClose() {},
    coverRenderer(instance, td, row, col, prop, value, cellProperties) {
      var escaped = Handsontable.helper.stringify(value),
        img;
      img = document.createElement("IMG");
      img.style.width = "120px";
      img.style.marginTop = "4px";
      img.src = value;
      Handsontable.dom.addEvent(img, "mousedown", function(e) {
        console.log(e);
        e.preventDefault(); // prevent selection quirk
      });
      Handsontable.dom.empty(td);
      td.appendChild(img);
      return td;
    },
    importExcel() {
      this.dialogVisible = true;
    },
    /**
     * 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用。
     * @param f {@link Object}：当前上传的文件；
     * @param fs {@link Array}：当前文件列表；
     */
    elInFile(f, fs) {
      let _this = this;
      let inputDOM = this.$refs.inputer; // 通过DOM取文件数据
      this.file = event.currentTarget.files[0];
      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file;
      var reader = new FileReader(); //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function(f) {
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串
        var pt = this;
        var wb; //读取完成的数据
        var outdata;
        var reader = new FileReader();
        reader.onload = function(e) {
          var bytes = new Uint8Array(reader.result);
          var length = bytes.byteLength;
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          var XLSX = require("xlsx");
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: "base64"
            });
          } else {
            wb = XLSX.read(binary, {
              type: "binary"
            });
          } // outdata就是你想要的东西 excel导入的数据
          let importHeaderArr = [];
          let confirmHeaderArr = [];
          let dataArr = [];
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); // excel 数据再处理
          if (!outdata) {
            _this.$alert("请上传一个不为空的excel表格", "提示", {
              confirmButtonText: "确定",
              callback: () => {}
            });
            return false;
          }
          wb.Strings.map(item => {
            importHeaderArr.push(item.t);
            confirmHeaderArr.push(item.t);
          });
          // 导入的头部数组 只取前18个
          importHeaderArr = importHeaderArr.filter((item, index) => {
            return index < 18;
          });
          confirmHeaderArr = confirmHeaderArr.filter((item, index) => {
            return index < 18;
          });
          if (_this.templateHeaderList.indexOf("货号") != -1) {
            _this.templateHeaderList.splice(
              _this.templateHeaderList.indexOf("货号"),
              1
            );
          }
          console.log("导入的表头数据", importHeaderArr);
          //下拉选择框的数据
          _this.importHeadList = importHeaderArr;
          // 赋值导入的头部数组变量`
          _this.confirmImportHeadList = confirmHeaderArr;
          _this.maxRows = 9999;
          _this.type = 1;
          _this.outDataList = outdata;
          console.log("outData", _this.outDataList);
          _this.step = 2;
          _this.dialogVisible = false;
        };
        reader.readAsArrayBuffer(f);
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    }
  }
};
</script>

<style rel="stylesheet/less" lang="less" scoped>
.handleDiv {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  height: 60px;
  padding: 0 25px;
  border-top: 1px solid #dfdfdf;
  border-bottom: 1px solid #dfdfdf;
}

.timeline {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  margin-top: -20px;
  width: 128px;
  height: 4px;
  background: #d6d6d6;
  .precent {
    position: absolute;
    width: 64px;
    height: 4px;
    z-index: 99;
    background: #2878ff;
  }
  .item {
    font-size: 12px;
    display: flex;
    align-items: center;
    flex-direction: column;
    .dot {
      margin-top: 20px;
      margin-bottom: 5px;
      width: 15px;
      height: 15px;
      background: #d6d6d6;
      border-radius: 15px;
    }
  }
}

.matcheCard {
  width: 1200px;
  margin: 0 auto;
  margin-top: 50px;
  .matcheItem {
    font-size: 16px;
    padding: 12px 30px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    img {
      height: 8px;
    }
    .title {
      width: 100px;
      text-align: right;
    }
  }
}

.noData_img {
  width: 250px;
  margin-top: 110px;
}

.getAll {
  font-size: 16px;
  margin-bottom: 4px !important;
  &:hover {
    cursor: pointer;
    transition: all 0.3s;
    opacity: 0.8;
  }
}

.el-upload__text {
  font-size: 12px;
  p {
    margin: 0;
    line-height: 20px;
  }
}

.hy_item {
  color: #000000;
  margin-bottom: 25px;
  label {
    width: 70px;
    font-size: 16px;
    display: inline-block;
  }
}

.upload-demo {
  margin: 20px 0;
  text-align: center;
}

.noData {
  margin-top: 15px;
  color: #909399;
}

.downLoad {
  margin: 0 4px;
  cursor: pointer;
  color: #2878ff;
}

.dialog-footer {
  position: relative;
}

.footerLeft {
  position: absolute;
  text-align: left;
  font-size: 12px;
  width: 200px;
  p {
    margin: 0;
  }
}
</style>